<?php
namespace app\common\model;

use think\Model;
use think\Db;
use think\model\concern\SoftDelete;

class UserModel extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    protected $name = 'user';

    /**
     * 请求参数格式化
     *
     * @param  array  $param [description]
     * @return [type]        [description]
     */
    public function param_format($param = array())
    {
        $param['limit'] = empty($param['limit']) ? 10 : $param['limit'];
        $param['page']  = empty($param['page']) ? 1 : $param['page'];
        $param['phone'] = empty($param['phone']) ? '' : $param['phone'];
        $param['type'] = !isset($param['type']) ? -1 : $param['type'];

        return $param;
    }

    /**
     * 获取用户信息
     *
     * @return [type] [description]
     */
    public function getBaseInfoByUid($uid)
    {
        return $this->where(['uid' => $uid])
            ->field('uid, type, username, headimg, balance')
            ->find();
    }

    /**
     * 获取uid根据账号
     */
    public function getUidByUser($user)
    {
        return $this->getFieldByPhone($user, 'uid');
    }

    /**
     * 获取用户昵称
     *
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getUserName($uid)
    {
        return $this->getFieldByUid($uid, 'username');
    }

    /**
     * 关联房间
     *
     * @return [type] [description]
     */
    public function room()
    {
        return $this->hasOne('room_model', 'uid', 'uid');
    }

    /**
     * 余额足够
     *
     * @return boolean [description]
     */
    public function isBalanceEnough($uid, $neetAmount)
    {
        $info = $this->where(['uid' => $uid])->find();
        if ($neetAmount > $info['balance']) {
            return false;
        }
        return true;
    }

    /**
     * 扣除玩家低注
     *
     * @param  [type] $pos      [description]
     * @param  [type] $low_note [description]
     * @return [type]           [description]
     */
    public function buckleLowNote($pos, $low_note)
    {
        foreach ($pos as $k => $v) {
            $this->incBalance($v, 0-$low_note);
        }
        return true;
    }

    /**
     * 增加余额
     *
     * @param  [type] $uid    用户id
     * @param  [type] $amount 数目
     * @return [type]         [description]
     */
    public function incBalance($uid, $amount)
    {
        return $this->where(['uid' => $uid])
            ->setInc('balance', $amount);
    }
}
